<script setup>
import {User, Lock} from '@element-plus/icons-vue'
import {ref} from 'vue'
import adminApi from '@/api/admin.js'
import userApi from '@/api/user.js'
import coachApi from '@/api/coach.js'
import {ElMessage} from "element-plus";
import {useTokenStore} from '@/store/token.js'
const tokenStore = useTokenStore();
import {useRouter} from 'vue-router'
const router = useRouter()
import jwtUtil from '@/utils/jwtUtil.js'
import captchaApi from "@/api/captcha.js";

//定义数据模型
const loginInfoDTO = ref({
        name: '',
        password: '',
        type: 1,
        captcha:'',
        uuid:''
    })
//表单校验模型
const rules = ref({
    name: [
        {required: true, message: '请输入用户名', trigger: 'blur'},
        {min: 5, max: 16, message: '用户名的长度必须为5~16位', trigger: 'blur'}
    ],
    password: [
        {required: true, message: '请输入密码', trigger: 'blur'},
        {min: 3, max: 16, message: '密码长度必须为3~16位', trigger: 'blur'}
    ]
})

const login = () => {
    if (loginInfoDTO.value.type === 1) {
        // 管理员登录
        adminApi.login(loginInfoDTO.value).then(result => {
            console.log(result)
            if (result.code == 0) {
                ElMessage.success(result.msg ? result.msg : '登录成功')
                //把得到的token放到pinia中
                tokenStore.setToken(result.data)
                // 从token中解析管理员ID
                const adminId = jwtUtil.getUserId(result.data)
                if (adminId) {
                    tokenStore.setUserId(adminId)
                    console.log('设置管理员ID:', adminId)
                }
                localStorage.setItem('type', 1)
                //TODO 路由到首页 /
                router.push('/admin/chart')
            } else {
                //ElMessage.error(result.msg)
                loadCaptcha()
            }
        })
    } else if (loginInfoDTO.value.type === 2) {
        // 用户登录
        console.log('用户登录请求:', loginInfoDTO.value);
        userApi.login(loginInfoDTO.value).then(result => {
            console.log('登录响应结果:', result)
            if (result.code == 0) {
                ElMessage.success(result.msg ? result.msg : '登录成功')
                tokenStore.setToken(result.data)
                // 从token中解析用户ID
                const userId = jwtUtil.getUserId(result.data)
                if (userId) {
                    tokenStore.setUserId(userId)
                    console.log('设置用户ID:', userId)
                }
                localStorage.setItem('type', 2)
                router.push('/user/chart')
            } else {
                //ElMessage.error(result.msg)
                loadCaptcha()
            }
        })
    } else if (loginInfoDTO.value.type === 3) {
        // 教练登录
        console.log('教练登录请求:', loginInfoDTO.value);
        coachApi.login(loginInfoDTO.value).then(result => {
            console.log('教练登录响应结果:', result)
            if (result.code == 0) {
                ElMessage.success(result.msg ? result.msg : '登录成功')
                //把得到的token放到pinia中
                tokenStore.setToken(result.data)
                // 从token中解析教练ID
                const coachId = jwtUtil.getUserId(result.data)
                if (coachId) {
                    tokenStore.setCoachId(coachId)
                }
                localStorage.setItem('type', 3)
                router.push('/coach/chart')
            } else {
                //ElMessage.error(result.msg)
                loadCaptcha()
            }
        })
    }
}

const captcha = ref('')
const loadCaptcha = () => {
    captchaApi.captcha().then(result => {
        captcha.value = result.data.captcha
        loginInfoDTO.value.uuid = result.data.uuid
    })
}

loadCaptcha()


</script>

<template>
    <div class="login-bg">
        <!-- 登录表单 -->
        <el-form class="form-login" ref="form" size="large" autocomplete="off" :model="loginInfoDTO" :rules="rules">
            <el-form-item>
                <h1>登录</h1>
            </el-form-item>
            <el-form-item prop="name">
                <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="loginInfoDTO.name"></el-input>
            </el-form-item>
            <el-form-item prop="password">
                <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码"
                          v-model="loginInfoDTO.password"></el-input>
            </el-form-item>
            <el-form-item prop="captcha">
                <el-input name="captcha" v-model="loginInfoDTO.captcha" placeholder="验证码" auto-complete="off" prefix-icon="el-icon-refresh"></el-input>
                <img width="160px" :src="captcha" @click="loadCaptcha" alt="验证码"/>
            </el-form-item>
            <el-form-item prop="type">
                <el-radio-group v-model="loginInfoDTO.type">
                    <el-radio :value="1" size="large">管理员</el-radio>
                    <el-radio :value="2" size="large">用户</el-radio>
                    <el-radio :value="3" size="large">教练</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item class="flex">
                <div class="flex">
                    <el-checkbox>记住我</el-checkbox>
                    <el-link type="primary" :underline="false">忘记密码？</el-link>
                </div>
            </el-form-item>
            <!-- 登录按钮 -->
            <el-form-item>
                <el-button class="button" type="primary" auto-insert-space @click="login">登录</el-button>
            </el-form-item>
        </el-form>
    </div>

</template>

<style scoped>

.login-bg {
    height: 100%;
    background-repeat: no-repeat;
    background-position: center;
    background-attachment: fixed;
    background-size: cover;
}

.form-login {
    width: 280px;
    padding: 20px;
    position: absolute;
    top: 20%;
    left: calc(50% - 150px);
    background-color: #FFF;
    box-shadow: 10px 10px 30px #000;
}

.flex {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.button {
    width: 100%;
}
</style>